<template>
  <div class="voice">
    <el-header>
      <div class="main-NAV">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item>机油保养邀约</el-breadcrumb-item>
          <el-breadcrumb-item>学习与考试</el-breadcrumb-item>
          <el-breadcrumb-item>客户档案</el-breadcrumb-item>
          <el-breadcrumb-item>场景1</el-breadcrumb-item>
        </el-breadcrumb>
        <div class="startCss" @click="toResult">{{ startks == 2 ? 'END' : 'START' }}</div>
      </div>
    </el-header>
    <audio id="player" :src="Mp3url" controls autoplay style="position: absolute; z-index: -1"></audio>
    <div class="voice-Content">
      <header>
        Sensitive Word :
        <span v-for="item in SensitiveWordsArr">{{ item }}</span>
      </header>
      <div class="vadio-Content">
        <video id="videoCamera" :width="videoWidth" :height="videoHeight" autoplay></video>
        <canvas id="canvasCamera" :width="videoWidth" :height="videoHeight" style="display: none"></canvas>
        <div class="Line"></div>
      </div>
      <div class="vadio-bottom">
        <span>Speed：{{ SpeakSpeed[SpeakSpeed.length - 1] * 60 || 0 }}字/分钟</span>
        <span>Expression：{{ assetsData.emotionName2[ShowExpressionList[ShowExpressionList.length - 1]] || 'neutral' }}</span>
        <img @click="stopExam" v-if="isStopExam" src="../../assets/img/play.png" alt="" />
        <img @click="stopExam" v-else src="../../assets/img/noplay.png" alt="" />
      </div>
    </div>
    <div class="YYcontentCSS">
      <div class="YYcontent" ref="Maincontxt" id="Maincontxt">
        <ul>
          <li v-for="(item, index) in ContxtList" :key="index" :class="item.user == 1 ? 'contextlef' : 'contextrig'">
            <img src="../../assets/img/user.png" alt="" v-if="item.user == 1" style="margin-right: 12px" />
            <p v-show="item.contxt">{{ item.contxt }}</p>
            <img src="../../assets/img/bmw.png" alt="" v-if="item.user == 2" style="margin-left: 12px" />
          </li>
          <li class="contextrig" v-if="ContxtList.length % 2 != 0 && txtstr.contxt">
            <p>{{ txtstr.contxt }}</p>
            <img src="../../assets/img/bmw.png" alt="" style="margin-left: 12px" />
          </li>
        </ul>
      </div>
    </div>
    <div class="vadio-tips">
      <div>
        <p class="good" v-for="item in AssessmentList" :key="item" v-if="paperData[item]">
          <img src="../../assets/img/good.png" alt="" />
          <span>{{ paperData[item] }}</span>
          <!-- <span>{{ item }}</span> -->
        </p>
        <!-- <p class="good">
          <img src="../../assets/img/good.png" alt="" />
          <span>报出岗位</span>
        </p>
        <p class="bad">
          <img src="../../assets/img/bad.png" alt="" />
          <span>报出经销商</span>
        </p> -->
      </div>
      <!-- <div>
        <i @click="stopExam">{{ isStopExam ? '开始说话' : '结束说话' }}</i>
      </div> -->
    </div>
  </div>
</template>
<script>
import Recorder from '../../utils/recorder.js';

import assetsData from '../../utils/assets.js';

const recorder = new Recorder({
  sampleBits: 16, // 采样位数，支持 8 或 16，默认是16
  sampleRate: 16000, // 采样率，支持 11025、16000、22050、24000、44100、48000，根据浏览器默认值，我的chrome是48000
  numChannels: 1, // 声道，支持 1 或 2， 默认是1
  compiling: true, //(0. x版本中生效, 1. x增加中) // 是否边录边转换，默认是false
});
var SOCKET = null;
// 防抖
const delay = (function () {
  let timer = 0;
  return function (callback, ms) {
    clearTimeout(timer);
    timer = setTimeout(callback, ms);
  };
})();

const emotion2 = {
  none: '10',
  smile: '50',
  laugh: '30',
  angry: '-10',
  disgust: '-30',
  fear: '-10',
  happy: '50',
  sad: '-10',
  surprise: '0',
  neutral: '0',
  pouty: '0',
  grimace: '0',
};
const emotion = {
  angry: '愤怒',
  disgust: '厌恶',
  fear: '恐惧',
  happy: '高兴',
  sad: '伤心',
  surprise: '惊讶',
  neutral: '无表情',
  pouty: '撅嘴',
  grimace: '鬼脸',
};
const expression = {
  none: '不笑',
  smile: '微笑',
  laugh: '大笑',
};
export default {
  data() {
    return {
      assetsData: assetsData,
      // info: {},

      startks: 1, //开始考试
      vol: '', // 声音大小
      StopVoice: null,
      info: {
        vtype: '首次进店',
        username: 'lxlxbaba',
        cartype: '宝马',
        lx: '场景1', // 考试类型
      },
      expression: expression,
      emotion: emotion,
      ExpressionList: [], //表情列表
      ExpressionContent: '', //表情
      ShowExpressionList: [], // 表情曲线
      PhotoAdmin: 1,
      StartExam: 1, // 是否开始考试
      examid: '', // 考试id
      RecorderAdmin: 1, // 摄像头是否可用 语音是否可用 0 不可用
      StartVoice: 0, // 是否开始录音
      vociedata: '', // 录音数据
      chunk: 0, // 当前切片
      vtypelist: [], // 职位列表
      usernamelist: [], // 人员列表
      cartypelist: [], // 车系列表

      //  摄像头
      videoWidth: 963,
      videoHeight: 430,
      imgSrc: '', // 摄像头图像路径
      thisCancas: null,
      thisContext: null,
      thisVideo: null,

      beginloading: false, // 是否开始录音
      isSocket: false, //是否有心跳
      timertxt: null,
      txtstr: {
        starttime: '',
        endtime: '',
        user: '',
        id: '',
        contxt: '',
        endobj: {},
      },
      // 语音文本列表
      ContxtList: [],
      // 语音
      //   用户信息
      timer: null, // 时间
      Mp3url: '', //  Mp3url  语音播放
      user: {
        timer: '',
      },
      nowdate: 600000, //倒计时    10分钟
      isStopExam: false, // 是否暂停考试
      showtxt: '',
      Serves: false,
      nowtxt: '', //正在说的话术
      SpeakSpeed: [],
      issocketclose: true, //长连接是否断开

      VadioEnd: false,

      AssessmentList: [], // 触发考核点
      SensitiveWordsArr: [], // 敏感词
      isscoll: true,
      examType: 3, // 试卷
      paperData: {},
    };
  },
  methods: {
    // 开始考试
    BenginExam() {
      let data = {
        cid: 'bztest',
        vtype: this.info.vtype,
        username: this.info.username,
        cartype: this.info.cartype,
      };
      // if (this.RecorderAdmin === 0) {
      //   alert('麦克风初始化失败，请同意使用麦克风！');
      //   // return
      // }
      // if (this.PhotoAdmin === 0) {
      //   alert('调用摄像头失败，请检查是否连接摄像头！');
      //   // return
      // }

      this.$axios.Postdata('manage/Voicerecordreport.asmx/createExam', { data: JSON.stringify(this.$Help.QMdata(data)) }).then(res => {
        console.log(res);
        if (res.errcode === 0) {
          this.examid = res.examid || '';
          localStorage.setItem('examid', this.examid);
          this.StartVoice = 1;
        }
      });
    },

    // 调用权限（打开摄像头功能）
    getCompetence() {
      var _this = this;
      this.thisCancas = document.getElementById('canvasCamera');
      this.thisContext = this.thisCancas.getContext('2d');
      this.thisVideo = document.getElementById('videoCamera');
      // 旧版本浏览器可能根本不支持mediaDevices，我们首先设置一个空对象
      if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {};
      }
      // 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象
      // 使用getUserMedia，因为它会覆盖现有的属性。
      // 这里，如果缺少getUserMedia属性，就添加它。
      console.log(navigator.mediaDevices);
      if (navigator.mediaDevices.getUserMedia === undefined) {
        navigator.mediaDevices.getUserMedia = function (constraints) {
          // 首先获取现存的getUserMedia(如果存在)
          var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.getUserMedia;
          // 有些浏览器不支持，会返回错误信息
          console.log(getUserMedia);
          // 保持接口一致
          if (!getUserMedia) {
            return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
          }
          // 否则，使用Promise将调用包装到旧的navigator.getUserMedia
          return new Promise(function (resolve, reject) {
            getUserMedia.call(navigator, constraints, resolve, reject);
          });
        };
      }
      var constraints = {
        audio: false,
        video: {
          width: this.videoWidth,
          height: this.videoHeight,
          transform: 'scaleX(-1)',
          facingMode: 'user',
        },
      };
      navigator.mediaDevices
        .getUserMedia(constraints)
        .then(function (stream) {
          // 旧的浏览器可能没有srcObject
          if ('srcObject' in _this.thisVideo) {
            _this.thisVideo.srcObject = stream;
          } else {
            // 避免在新的浏览器中使用它，因为它正在被弃用。
            _this.thisVideo.src = window.URL.createObjectURL(stream);
          }
          _this.thisVideo.onloadedmetadata = function (e) {
            _this.thisVideo.play();
          };
        })
        .catch(err => {
          console.log(err);
          this.PhotoAdmin = 0;
          alert('调用摄像头失败，请检查是否连接摄像头！');
        });
    },

    //  绘制图片（拍照功能）
    setImage() {
      if (this.VadioEnd) return;
      var _this = this;
      // 点击，canvas画图
      _this.thisContext.drawImage(_this.thisVideo, 0, 0, _this.videoWidth, _this.videoHeight);
      // 获取图片base64链接
      var image = this.thisCancas.toDataURL('image/jpeg');
      //  base64 转文件流

      let imgdata = _this.dataURLtoFile(image, `${new Date().getTime()}.png`);

      // 上传图片
      this.UploadImageFun(imgdata);
    },

    // base64转文件
    dataURLtoFile(dataurl, filename) {
      var arr = dataurl.split(',');
      var mime = arr[0].match(/:(.*?);/)[1];
      var bstr = atob(arr[1]);
      var n = bstr.length;
      var u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, {
        type: mime,
      });
    },

    // 暂停录音
    stopExam() {
      let that = this;
      if (that.isStopExam) {
        // 打开长连接
        that.openWebSocket();
        that.isStopExam = false;
        that.countdown(that.nowdate);
        // 服务请求结束
        setTimeout(() => {
          that.txtstr.id = new Date().getTime();
          that.txtstr.endobj = {};
        }, 1000);
      } else {
        console.log('暂停说话');
        SOCKET.send(
          JSON.stringify({
            type: 'end',
          })
        );
        that.isStopExam = true;
        SOCKET.close();
        if (!this.txtstr.contxt) return;
        setTimeout(() => {
          this.ContxtList.push({
            user: 2,
            id: this.txtstr.id,
            contxt: this.txtstr.contxt,
          });
          //  终止这段话，然后获取回术
          that.GetAnswerSentenceFun();
        }, 1000);
      }
    },

    // 关闭摄像头
    stopNavigator() {
      console.log(this.thisVideo);
      this.thisVideo.srcObject.getTracks()[0].stop();
    },

    //  处理语音转译
    Pcontent(data) {
      let txt = '';
      let timerarr = [];
      // 取 key
      for (let key in data.endobj) {
        timerarr.push(key);
      }
      // 排序
      timerarr.sort(function (a, b) {
        return a - b;
      });
      txt = '';
      timerarr.forEach(item2 => {
        txt += data.endobj[item2];
      });
      data.contxt = txt;
      this.SpeakSpeed.push(Math.ceil((data.contxt.length / (data.endtime - data.starttime || 0)) * 1000));
      // this.DrowEcharts(
      //   {
      //     time: '',
      //     DataArray: this.SpeakSpeed,
      //   },
      //   '2'
      // );
      // console.log(data);
    },
    // 添加内容    文字处理
    Putcontext(data) {
      let that = this;
      // console.log(data)
      let flag = false;
      this.ContxtList.forEach(item => {
        if (item.id == data.id) {
          flag = true;
        }
        if (item.user == 2) {
          let timerarr = [];
          // 取 key
          for (let key in item.endobj) {
            timerarr.push(key);
          }
          // 排序
          timerarr.sort(function (a, b) {
            return a - b;
          });
          item.starttime = timerarr[0];
          item.contxt = '';
          timerarr.forEach(item2 => {
            item.contxt += item.endobj[item2];
          });
        }
      });
      if (!flag) {
        this.ContxtList.push(data);
      }
    },

    // 开始录音
    startRecording: function () {
      recorder.start().then(
        () => {
          // this.GetAnswerSentenceFun()
          let that = this;
          // 开始录音
          console.log('录音已开始');
          this.countdown(this.nowdate); // 开始考试倒计时开始
          this.StartExam = 2;
          this.startks = 2;
          that.ContxtList.push({
            user: 1,
            id: new Date().getTime(),
            contxt: '考试已开始，请点击视频框下方按钮开始对话',
          });
          this.isStopExam = true;

          that.openWebSocket();
          // 定时上传图片
          setTimeout(() => {
            that.setImage();
          }, 3000);
        },
        error => {
          // 出错了
          console.log(`${error.name} : ${error.message}`);
        }
      );
    },

    // 停止录音
    stopRecording: function () {
      recorder.stop();
      this.beginloading = false;
      console.log('停止录音');
      // clearInterval(this.timertxt)
      this.StartVoice = 0;
      // 结束
      SOCKET.send(
        JSON.stringify({
          type: 'end',
        })
      );
      this.endExamFun();
    },

    // 开始倒计时
    countdown(timer) {
      // timer     结束时间
      if (this.isStopExam) return;
      const end = new Date().getTime() + this.nowdate;
      const now = new Date().getTime();
      const msec = end - now;
      if (msec < 0) return;
      const that = this;
      setTimeout(() => {
        that.user.timer = new Date(msec).Format('mm:ss');
        this.nowdate = end - new Date().getTime();
        that.countdown();
      }, 1000);
    },

    // 播放 Mp3
    PlayerMp3(data) {
      var player = new Audio(data);
      player.play();
    },

    //  终止一句话
    stopvoiceFun() {
      if (!this.txtstr.contxt) return;
      // 修改
      if (this.nowtxt) {
        this.ContxtList.push({
          // starttime: 0,
          // endtime: '',
          user: 2,
          id: this.txtstr.id,
          contxt: this.nowtxt,
          // endobj: {},
        });
      } else {
        this.ContxtList.push({
          // starttime: 0,
          // endtime: '',
          user: 2,
          id: this.txtstr.id,
          contxt: this.txtstr.contxt,
          // endobj: {},
        });
      }

      // console.log('停止录音')
      //  终止这段话，然后获取回术
      this.GetAnswerSentenceFun();
    },

    //  链接socket
    openWebSocket() {
      let that = this;
      console.log(that);
      if ('WebSocket' in window) {
        let data = {
          Appid: '1256599233',
          SecretId: 'AKIDBahiZEs2BDFByhRdyAf5KNEvmdOzCnup',
        };
        const obj = that.$Help.QMFun(data);
        SOCKET = new WebSocket(`wss://${obj.SecretKey}&signature=${obj.signature}`);
        console.log('链接成功');
      } else {
        console.log('当前浏览器 Not support websocket');
        // return
      }
      SOCKET.onopen = res => {
        console.log('已连接');
        let that = this;
        that.issocketclose = false;
        that.timertxt = setInterval(() => {
          let voice = recorder.getNextData();
          if (that.issocketclose) return;
          if (voice.length != 0) {
            if (voice.length >= 2) {
              voice.forEach(element => {
                SOCKET.send(element);
              });
            } else {
              SOCKET.send(voice[0]);
            }
          }
        }, 40);
      };

      // 接收信息
      (SOCKET.onmessage = res => {
        let that = this;
        const data = JSON.parse(res.data);
        if (that.isStopExam || !data.result.voice_text_str) return;
        if (data.result.voice_text_str) {
          this.txtstr.endtime = data.result.end_time;
          this.txtstr.endobj[data.result.start_time] = data.result.voice_text_str;
          this.txtstr.user = 2;
          this.Pcontent(this.txtstr);
          this.showtxt = this.txtstr;
        }
      }),
        // socket  关闭
        (SOCKET.onclose = res => {
          console.log('SOCKET暂时关闭');
          that.issocketclose = true;
          if (that.StartVoice === 1 && !that.isStopExam) {
            // 正在录音
            that.openWebSocket();
          }
        }),
        (SOCKET.onerror = () => {
          // 连接错误
          console.log('连接错误');
        });
    },

    // 提交分片数据
    uploadVoiceFun(byts) {
      let data1 = {
        examid: this.examid,
        chunk: byts.chunk,
      };
      let formdata = new FormData();
      formdata.append('byte', byts.byts);
      formdata.append('data', JSON.stringify(this.$Help.QMdata(data1)));
      this.$axios.formatPostData('manage/Voicerecordreport.asmx/uploadVoice', formdata).then(res => {
        if (res.errcode != 0) {
          // 上传错误重新上传
          this.uploadVoiceFun(byts);
        }
      });

      // $.ajax({
      //   type: 'post', //默认get
      //   url: `${url}/manage/Voicerecordreport.asmx/uploadVoice`, //默认当前页
      //   data: formdata,
      //   dataType: 'json',
      //   cache: false,
      //   processData: false,
      //   contentType: false,
      //   success: res => {
      //     //请求成功回调
      //     console.log(res);
      //     if (res.errcode != 0) {
      //       // 上传错误重新上传
      //       this.uploadVoiceFun(byts);
      //     }
      //   },
      //   error: function (e) {
      //     //请求超时回调
      //     if (e.statusText == 'timeout') {
      //       alert('请求超时');
      //     }
      //   },
      // });
    },

    //  获取动态人物表情
    getExamEmotionFun() {
      let data = {
        examid: this.examid,
      };

      this.$axios
        .Postdata('manage/Voicerecordreport.asmx/getExamEmotion', {
          data: JSON.stringify(this.$Help.QMdata(data)),
        })
        .then(res => {
          //请求成功回调
          // console.log(res)
          let DataArray = [];
          let time = [];
          // 处理表情
          res.forEach(item => {
            this.ExpressionList.forEach(item2 => {
              if (item2.count != item.count && item.emotion == item2.emotion) {
                this.ShowExpressionList.push(item.emotion);
              }
            });
            let idx = this.ExpressionList.findIndex(item3 => item.emotion != item3);
            if (idx == -1) {
              this.ShowExpressionList.push(item.emotion);
            }
          });
          this.ExpressionList = res;
          // let ShowExpressionListCopy = this.ShowExpressionList
          if (!this.isStopExam) {
            this.ShowExpressionList.forEach((item, index) => {
              if (item) {
                DataArray.push(emotion2[item] || '0');
              } else {
                DataArray.push(0);
              }
              time.push(index + 1);
            });
          }
          setTimeout(() => {
            this.setImage();
          }, 2000);
        });
    },

    //  上传图片
    UploadImageFun(data) {
      let formdata = new FormData();
      formdata.append('image', data);
      formdata.append(
        'data',
        JSON.stringify(
          this.$Help.QMdata({
            examid: this.examid,
          })
        )
      );
      try {
        this.$axios.formatPostData('manage/Voicerecordreport.asmx/uploadExamJpg', formdata).then(res => {
          if (res.errcode == 0) {
            //  获取人物表情
            this.getExamEmotionFun();
          }
        });
      } catch {
        setTimeout(() => {
          this.setImage();
        }, 2000);
      }
    },

    //  录音 结束   提交总数据
    endExamFun() {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      });
      recorder.stop();
      let data = {
        examid: this.examid,
        chunk: this.chunk,
        Txtcontent: ``,
        vtype: this.info.vtype,
        cid: 'bztest',
      };
      data.Txtcontent = this.ContxtFun(this.ContxtList);
      let blobdata = new Blob([recorder.getWAV()], {
        type: 'audio/wav',
      });

      let formdata = new FormData();
      formdata.append('byte', blobdata);
      formdata.append('data', JSON.stringify(this.$Help.QMdata(data)));

      this.$axios.formatPostData('manage/Voicerecordreport.asmx/endExam', formdata).then(res => {
        //请求成功回调
        loading.close();
        if (res.errcode == 0) {
          this.VadioEnd = true;

          localStorage.setItem('ShowExpressionList', JSON.stringify(this.ShowExpressionList)); //表情曲线列表
          localStorage.setItem('SpeakSpeed', JSON.stringify(this.SpeakSpeed)); //语速
          localStorage.setItem('ExpressionList', JSON.stringify(this.ExpressionList)); //表情触发次数
          // 跳转页面
          this.$router.push({ name: 'ResultTwo' });
        }
      });
    },

    // 语音内容处理

    ContxtFun(date) {
      let str = ``;
      date.forEach(item => {
        let timearr = [this.TimeProcessingFun(item.starttime), this.TimeProcessingFun(item.endtime)];
        let txt = `[${timearr}]  ${item.contxt}   \n`;
        str += txt;
      });
      return str;
    },
    //  时间处理   格式  1:1.000     1分1秒
    TimeProcessingFun(time) {
      if (time == 0) {
        return `0:0.00`;
      }
      let mm = Math.floor(time / 1000 / 60);
      let ss = (time - mm * 60000) / 1000;
      return `${mm}:${ss}`;
    },

    //  获取录音类型
    RecordingtypeFun() {
      this.$axios.Postdata('manage/Voicerecordreport.asmx/getvtype', { cid: 'bztest', actname: '' }).then(res => {
        console.log(res);
        this.vtypelist = res;
        this.info.vtype = res[0].vtype;
        this.GetusernameFun();
      });
    },
    //  获取人员列表
    GetusernameFun() {
      this.$axios.Postdata('manage/Voicerecordreport.asmx/getusername', { cid: 'bztest', actname: '', vtype: this.info.vtype }).then(res => {
        console.log(res);
        this.info.username = res[0].username;
        this.usernamelist = res;
      });
    },

    //获取回术
    GetAnswerSentenceFun() {
      // debugger
      let that = this;
      that.Serves = true;
      let starttime = new Date().getTime();
      let sentence = '';
      this.ContxtList.forEach(item => {
        if (item.user == 2) {
          sentence = item.contxt;
        }
      });
      this.SensitiveWordsArr = assetsData.SensitiveWords(sentence, '1');
      let data = {
        data: JSON.stringify(
          this.$Help.QMdata({
            sentence: sentence,
            vtype: this.info.vtype,
            cartype: this.info.cartype,
            paperid: this.examType, // 试卷类型
            examid: this.examid, // 新增考试id
          })
        ),
      };

      this.$axios.Postdata('manage/Voicerecordreport.asmx/getAnswerSentence', data).then(res => {
        // if (res.errcode == 1) return
        this.AssessmentList = [];
        let arr = res.recogsentence ? res.recogsentence.split(',') : [];
        arr.forEach(item => {
          this.AssessmentList.push(item.replace(/（/g, '(').replace(/）/g, ')'));
        });

        console.log(res);
        that.txtstr.contxt = '';
        let MP3url = this.dataURLtoFile(`data:audio/mpeg;base64,` + res.audio, 'luyin');
        this.Mp3url = URL.createObjectURL(MP3url); // z转换 MP3播放
        let obj = {
          starttime: starttime,
          endtime: new Date().getTime(),
          user: 1,
          id: new Date().getTime(),
          contxt: res.sentence,
        };
        this.isscoll = false;
        that.ContxtList.push(obj);

        // 服务请求结束
        setTimeout(() => {
          that.txtstr = {
            starttime: '',
            endtime: '',
            user: '',
            id: '',
            contxt: '',
            endobj: {},
          };
          that.txtstr.id = new Date().getTime();
          that.Serves = false;
          this.isscoll = true;
        }, Math.ceil(res.sentence.length / 4 - 0) * 1000);
      });
    },

    // 返回
    HistoryGoBack() {
      history.go(-1);
    },

    toResult() {
      if (this.startks == 1) {
        this.startRecording();
        return;
      }
      if (this.startks == 2) {
        // 结束考试
        this.endExamFun();
      }
    },
    paperDataFun() {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      });
      let data = { paperid: this.examType };
      this.$axios.Postdata('manage/Voicerecordreport.asmx/getPaperDetail', { data: JSON.stringify(this.$Help.QMdata(data)) }).then(res => {
        console.log(res);
        loading.close();
        // this.paperData = res;
        let obj = {};
        res.forEach(item => {
          let str = item.sentence.replace(/（/g, '(').replace(/）/g, ')');

          obj[str] = item.items;
        });
        this.paperData = obj;
      });
    },
  },
  mounted() {
    let that = this;

    // 查看是否支持录音
    console.log(Recorder, recorder);
    this.$nextTick(function () {
      Recorder.getPermission().then(
        () => {
          console.log('给权限了');
          this.RecorderAdmin = 1;
        },
        error => {
          console.log(`${error.name} : ${error.message}`);
        }
      );
    });
    // 开始考试
    this.BenginExam();
    // 获取录音类型
    this.RecordingtypeFun();
    // 调用摄像头
    this.getCompetence();
  },

  // 更新数据周期
  updated() {
    if (this.isStopExam && this.isscoll) return;
    var Maincontxt = this.$refs.Maincontxt;
    Maincontxt.scrollTop = Maincontxt.scrollHeight;
  },

  watch: {
    vociedata: function (newVal, oldVal) {
      if (newVal.fileSize >= 1024 * 1024) {
        let blobdata = new Blob([recorder.getWAV()], {
          type: 'audio/wav',
        });
        const data = {
          chunk: this.chunk,
          byts: blobdata,
        };
        this.chunk++;
        // // 发送文件
        this.uploadVoiceFun(data);
      }
    },
  },

  created() {
    this.paperDataFun();
  },
};
</script>
<style lang="less" scoped>
.voice {
  display: flex;
  flex-direction: column;
  height: 100%;
}
.voice-lef {
  flex: 1;
  padding-right: 8px;
}
.main-NAV {
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
}
.main-NAV .startCss {
  width: 96px;
  height: 32px;
  background: #9e0018;
  border-radius: 5px;
  font-size: 20px;
  line-height: 32px;
  text-align: center;
  color: #fff;
  cursor: pointer;
}
.main-NAV /deep/ .el-breadcrumb__item {
  /* background-color: #f2f2f2 !important; */
  color: #303030 !important;
  font-size: 16px !important;
  &:last-of-type .el-breadcrumb__inner {
    color: #9e0018 !important;
  }
}
.voice-Content {
  width: 963px;
  margin: 0 auto;
}
.voice-Content header {
  height: 32px;
  background: #ffecef;
  line-height: 32px;
  font-size: 16px;
  color: #333;
  box-sizing: border-box;
  padding: 0 11px;
  span {
    font-size: 14px;
    color: #9e0018;
  }
}
.vadio-Content {
  height: 430px;
  background-color: #282828;
  position: relative;
}
.Line {
  width: 205px;
  height: 205px;
  box-sizing: border-box;
  position: relative;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  /* border: 1px solid #03eed8; */
  box-sizing: border-box;
  background-image: url('../../assets/img/line.png');
  background-size: contain;
  background-repeat: no-repeat;
  z-index: 3;
}
.vadio-bottom {
  height: 45px;
  background-color: #3d3d3d;
  display: flex;
  align-items: center;
  box-sizing: border-box;
  font-size: 14px;
  padding-left: 10px;
}
.vadio-bottom span {
  display: inline-block;
  min-width: 230px;
  color: #fff;
}
.vadio-bottom img {
  width: 34px;
  height: 34px;
  display: inline-block;
}

/* 对话 */
.YYcontent {
  flex: 1;
  height: 200px;
  max-height: 200px;
  width: 100%;
  overflow-y: auto;
  border-radius: 4px;
}

.YYcontent img {
  width: 25px;
  height: 25px;
  display: inline-block;
  border-radius: 50%;
}

.YYcontent ul {
  padding: 0 10px;
}

.YYcontent ul li {
  width: 100%;
  list-style: none;
  align-items: flex-start;
  display: flex;
  padding: 10px 0px;
}

.contextlef {
  width: 100%;
  justify-content: flex-start;
}

.contextrig {
  justify-content: flex-end;
}

.YYcontent li p {
  padding: 5px 5px;
  background-color: #fff;
  border-radius: 5px;
  font-size: 14px;
  max-width: 35%;
  width: 35%;
  color: #303133;
  display: inline-block;
  line-height: 1.2;
}

.contextrig p {
  align-self: flex-end;
  /* background-color: #e4e4e4 !important; */
  color: #333 !important;
  border: 1px solid #9e0018;
}
.contextrig span {
  align-self: flex-end;
}
.YYcontentCSS {
  width: 963px;
  margin: 0 auto;
}

/* 提示 */
.vadio-tips {
  width: 963px;
  margin: 0 auto;
  display: flex;
  box-sizing: border-box;
  padding-bottom: 20px;

  align-items: center;
  justify-content: space-between;
}
.vadio-tips i {
  font-size: 12px;
  padding: 5px 20px;
  background-color: #9e0018;
  font-style: normal;
  border-radius: 4px;
  cursor: pointer;
  color: #fff;
}
.vadio-tips div:first-of-type {
  display: flex;
}
.vadio-tips p {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  padding: 5px 20px;
  background-color: #ffecef;
  margin-right: 20px;
  border-radius: 15px;
}
.vadio-tips p img {
  width: 19px;
  height: 19px;
  margin-right: 10px;
}
.vadio-tips .good {
  color: #9e0018;
}
.vadio-tips .bad {
  color: #8f8f8f;
}
#videoCamera {
  position: absolute;
  top: 0;
  z-index: 2;
}
</style>
